﻿#include "frmmanager.h"
#include "ui_frmmanager.h"
#include "config.h"
#include <qdebug.h>
#include <qfile.h>
#include "quiwidget.h"

FrmManager::FrmManager(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FrmManager)
{
    ui->setupUi(this);
    initForm();
}

FrmManager::~FrmManager()
{
    delete ui;
}

void FrmManager::initForm()
{
    //读取配置文件
    QString port = Config().GetValue("listener","port").toString();
    ui->txtListenPort->setText(port);
}

void FrmManager::append(FrmManager::MessageType type, const QString &data, bool clear)
{
    if (clear) {
        ui->txtMain->clear();
        return;
    }

    if(ui->ckShow->isChecked())
        return;

    //过滤回车换行符
    QString strData = data;
    strData = strData.replace("\r", "");
    strData = strData.replace("\n", "");

    //不同类型不同颜色显示
    QString strType;
    switch(type) {
    case Connect:
    {
        strType = "连接";
        ui->txtMain->setTextColor(QColor("darkgreen"));
    }
        break;
    case Receive:
    {
        strType = "接收";
        ui->txtMain->setTextColor(QColor("red"));
    }
         break;
    case Disconnect:
    {
        strType = "退出";
        ui->txtMain->setTextColor(QColor("darkgreen"));
    }
        break;
    }

    strData = QString("时间[%1] %2: %3").arg(TIMEMS).arg(strType).arg(strData);
    ui->txtMain->append(strData);
}

void FrmManager::clientConnected(const QString &ip, int port)
{
    QString str = QString("%1:%2").arg(ip).arg(port);
    if (ui->listWidget->findItems(str,0).count() == 0 )
    ui->listWidget->addItem(str);
    if(ui->listWidget->currentRow() == -1) {
        ui->listWidget->setCurrentRow(ui->listWidget->count()-1);
    }

    ui->labCount->setText(QString("共 %1 个连接").arg(ui->listWidget->count()));

    if(ShowConnectTcpServer)
        notify(ip, port, "客户端上线");
}

void FrmManager::clientDisconnected(const QString &ip, int port)
{
    int row = -1;
    QString str = QString("%1:%2").arg(ip).arg(port);
    for (int i = 0; i < ui->listWidget->count(); i++) {
        if (ui->listWidget->item(i)->text() == str) {
            row = i;
            break;
        }
    }

    delete ui->listWidget->takeItem(row);
    ui->labCount->setText(QString("共 %1 个连接").arg(ui->listWidget->count()));

    if(ShowConnectTcpServer)
        notify(ip, port, "客户端下线");
}

void FrmManager::notify(const QString &ip, int port, const QString &data)
{
    QString str = QString("[%1:%2] %3").arg(ip).arg(port).arg(data);
    bool error = (data.contains("下线") || data.contains("离线"));
    append(error ? MessageType::Disconnect : MessageType::Connect, str);
}

void FrmManager::clientRequested(const QString &ip, int port, const QString &data)
{

    QString buffer = decodeData(data.toLatin1(), HexReceiveTcpServer, AsciiTcpServer);
    QString str = QString("[%1:%2] %3").arg(ip).arg(port).arg(buffer);
    append(MessageType::Receive, str);
}

void FrmManager::serverListen(bool iblisten)
{
    isOk = iblisten;
}


QByteArray FrmManager::encodeData(const QString &data, bool hex, bool ascii)
{
    QByteArray buffer;
    if (hex) {
        buffer = QUIHelper::hexStrToByteArray(data);
    } else if (ascii) {
        buffer = QUIHelper::asciiStrToByteArray(data);
    } else {
        buffer = data.toLatin1();
    }
    return buffer;
}

QString FrmManager::decodeData(const QByteArray &data, bool hex, bool ascii)
{
    QString buffer;
    if (hex) {
        buffer = QUIHelper::byteArrayToHexStr(data);
    } else if (ascii) {
        buffer = QUIHelper::byteArrayToAsciiStr(data);
    } else {
        buffer = QString(data);
    }
    return buffer;
}

void FrmManager::on_btnListen_clicked()
{
    QString port = ui->txtListenPort->text();
    Config().SetValue("listener","port",port);
    if (ui->btnListen->text() == "监听") {
        listenerSettings=new QSettings("./Config.ini", QSettings::IniFormat);
        listenerSettings->beginGroup("listener");
        // Start the HTTP server
        pHttpListener = new HttpListener(listenerSettings, new RequestMapper());
        connect(pHttpListener, SIGNAL(httpConnected(QString, int)), this, SLOT(clientConnected(QString, int)));
        connect(pHttpListener, SIGNAL(httpDisconnected(QString, int)), this, SLOT(clientDisconnected(QString, int)));
        connect(pHttpListener, SIGNAL(httpRequested(QString, int,QString)), this, SLOT(clientRequested(QString, int,QString)));
        connect(pHttpListener, SIGNAL(serverOpen(bool)), this, SLOT(serverListen(bool)));
        isOk = true;
        if (isOk) {
            append(Connect, tr("服务器：%1 端口：%2 监听中...").arg(QUIHelper::getLocalIP()).arg(port));
            ui->btnListen->setText("关闭");
        } else {
            append(Connect, tr("服务器端口：%1 监听失败!").arg(port));
        }
    } else {
        pHttpListener->close();
        append(Disconnect,  tr("服务器：%1 端口：%2 监听关闭").arg(QUIHelper::getLocalIP()).arg(port));
        ui->btnListen->setText("监听");
    }
}

void FrmManager::on_btnClear_clicked()
{
    append(Connect, "", true);
}

void FrmManager::on_btnSave_clicked()
{
    QString data = ui->txtMain->toPlainText();
    if (data.length() <= 0) {
        return;
    }

    QString fileName = QString("%1/%2.txt").arg(QUIHelper::appPath()).arg(STRDATETIME);
    QFile file(fileName);
    if (file.open(QFile::WriteOnly | QFile::Text)) {
        file.write(data.toUtf8());
        file.close();
    }
    QUIHelper::showMessageBoxInfo("文件:《"+QString("%1.txt").arg(STRDATETIME)+"》保存成功!");
    on_btnClear_clicked();
}


void FrmManager::on_ckShowConnect_stateChanged(int arg1)
{
    Q_UNUSED(arg1)
    ShowConnectTcpServer = ui->ckShowConnect->isChecked();
}

void FrmManager::on_ckHexReceive_stateChanged(int arg1)
{
     Q_UNUSED(arg1)
    HexReceiveTcpServer = ui->ckHexReceive->isChecked();
}

void FrmManager::on_ckAscii_stateChanged(int arg1)
{
    Q_UNUSED(arg1)
   AsciiTcpServer =  ui->ckAscii->isChecked();
}
